﻿@using NetCorePal.D3Shop.Domain.AggregatesModel.Identity.RoleAggregate
@using NetCorePal.D3Shop.Web.Admin.Client.Components.Identity
<a @onclick="ShowModal">配置权限</a>
<Modal Title="@("配置权限")"
       Visible="@_modalVisible"
       OnOk="Modal_HandleOk"
       OnCancel="() => _modalVisible = false"
       ConfirmLoading="@_modalConfirmLoading">
    <PermissionManager @ref="_permissionManagerComponent" @bind-AssignedPermissionCodes="_assignedPermissionCodes"/>
</Modal>

@code {
    [CascadingParameter] public RoleResponse Row { get; set; } = default!;
    
    [Inject] private IRolesService RolesService { get; set; } = default!;
    [Inject] private MessageService Message { get; set; } = default!;

    private bool _modalVisible;
    private bool _modalConfirmLoading;

    private List<string> _assignedPermissionCodes = [];
    PermissionManager _permissionManagerComponent = default!;

    private async Task ShowModal()
    {
        _modalVisible = true;
        _assignedPermissionCodes = await GetAssignedPermissionCodes(Row.Id);
        _permissionManagerComponent.ReRenderTree();
    }

    private async Task<List<string>> GetAssignedPermissionCodes(RoleId id)
    {
        var response = await RolesService.GetAssignedPermissionCodes(id);
        if (response.Success) return response.Data;
        _ = Message.Error(response.Message);
        return [];
    }

    private async Task Modal_HandleOk()
    {
        _modalConfirmLoading = true;
        StateHasChanged();
        var response = await RolesService.UpdateRolePermissions(Row.Id, _assignedPermissionCodes);
        _modalConfirmLoading = false;
        if (response.Success)
        {
            _modalVisible = false;
            _ = Message.Success("更新成功！");
        }
        else
        {
            _ = Message.Error(response.Message);
        }
    }

}